import { FilePreview } from "@/components/file";
import { FileIconImg } from "@/components/file/fileIcon";
import { useObserver } from "@/hooks";
import unknown from "@/assets/file-icons/unknown.png";
import { Checkbox } from "antd";
import PropTypes from "prop-types";
/**
 * 图片懒加载
 */
const FileIconItem = ({ item, checked = false, ...resProps }) => {
  const [targetRef, isIntersecting] = useObserver({ root: null, rootMargin: "0px 0px", threshold: 0.2 });

  if (isIntersecting === false) {
    return (
      <div ref={targetRef} className="file-icon-item">
        <img className="icon" src={unknown} alt="" loading="lazy" />
      </div>
    );
  }

  return (
    <div ref={targetRef} className="file-icon-item" data-checked={checked} {...resProps}>
      <div className="action" onClick={(e) => e.stopPropagation()}>
        <Checkbox className="checkbox" />
      </div>
      <FileIconImg
        className="icon"
        src={item.fullPath}
        type={item.isDirectory ? "folder" : item.suffix}
        loading="lazy"
      />
      <div className="file-info">
        <div className="file-name">{item.fileName}</div>
        <div className="file-time">{item.modifyTime}</div>
      </div>
    </div>
  );
};
FileIconItem.propTypes = {
  item: PropTypes.object.isRequired,
  checked: PropTypes.bool,
};

const FileIconLazyList = ({ items, onCallback }) => {
  return (
    <FilePreview items={items} dataProp="data-index" onCallback={onCallback}>
      <div className="file-icons-warrper">
        {items.map((item, index) => (
          <FileIconItem key={item.key} item={item} data-index={index} />
        ))}
      </div>
    </FilePreview>
  );
};

FileIconLazyList.propTypes = {
  items: PropTypes.array.isRequired,
  onCallback: PropTypes.func.isRequired,
};

export default FileIconLazyList;
